using Microsoft.Extensions.Logging;

namespace SeataNet.Core.Discovery
{
    /// <summary>
    /// 服务发现接口
    /// </summary>
    public interface IServiceDiscovery
    {
        /// <summary>
        /// 订阅服务
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="callback">服务变更回调</param>
        Task SubscribeAsync(string serviceName, Action<List<ServiceInstance>> callback);

        /// <summary>
        /// 取消订阅服务
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        Task UnsubscribeAsync(string serviceName);

        /// <summary>
        /// 获取服务实例列表
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns>服务实例列表</returns>
        Task<List<ServiceInstance>> GetInstancesAsync(string serviceName);

        /// <summary>
        /// 注册服务实例
        /// </summary>
        /// <param name="serviceInstance">服务实例</param>
        Task RegisterInstanceAsync(ServiceInstance serviceInstance);

        /// <summary>
        /// 注销服务实例
        /// </summary>
        /// <param name="serviceInstance">服务实例</param>
        Task DeregisterInstanceAsync(ServiceInstance serviceInstance);

        /// <summary>
        /// 发送心跳
        /// </summary>
        /// <param name="serviceInstance">服务实例</param>
        Task SendHeartbeatAsync(ServiceInstance serviceInstance);
    }

    /// <summary>
    /// 服务实例
    /// </summary>
    public class ServiceInstance
    {
        /// <summary>
        /// 服务名称
        /// </summary>
        public string ServiceName { get; set; } = string.Empty;

        /// <summary>
        /// 实例ID
        /// </summary>
        public string InstanceId { get; set; } = string.Empty;

        /// <summary>
        /// IP地址
        /// </summary>
        public string Ip { get; set; } = string.Empty;

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// 权重
        /// </summary>
        public double Weight { get; set; } = 1.0;

        /// <summary>
        /// 是否健康
        /// </summary>
        public bool Healthy { get; set; } = true;

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 元数据
        /// </summary>
        public Dictionary<string, string> Metadata { get; set; } = new Dictionary<string, string>();

        /// <summary>
        /// 集群名称
        /// </summary>
        public string ClusterName { get; set; } = "DEFAULT";

        /// <summary>
        /// 获取服务地址
        /// </summary>
        public string GetAddress()
        {
            return $"{Ip}:{Port}";
        }

        /// <summary>
        /// 获取服务URL
        /// </summary>
        /// <param name="protocol">协议 (http/https)</param>
        public string GetUrl(string protocol = "http")
        {
            return $"{protocol}://{Ip}:{Port}";
        }
    }
}
